//! # 管理 API 模块
//!
//! 提供 RESTful 管理接口，包括：
//! - 组件管理 API
//! - 系统信息 API  
//! - 配置管理 API
//! - 健康检查 API

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::Json,
    routing::{get, post, put, delete},
    Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

use crate::{AdminResult, AdminError, ComponentStatus};

/// API 响应结构
#[derive(Debug, Serialize)]
pub struct ApiResponse<T> {
    pub success: bool,
    pub data: Option<T>,
    pub message: String,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

impl<T> ApiResponse<T> {
    pub fn success(data: T) -> Self {
        Self {
            success: true,
            data: Some(data),
            message: "成功".to_string(),
            timestamp: chrono::Utc::now(),
        }
    }

    pub fn error(message: String) -> ApiResponse<()> {
        ApiResponse {
            success: false,
            data: None,
            message,
            timestamp: chrono::Utc::now(),
        }
    }
}

/// 组件信息
#[derive(Debug, Serialize, Deserialize)]
pub struct ComponentInfo {
    pub name: String,
    pub version: String,
    pub status: ComponentStatus,
    pub config: serde_json::Value,
    pub last_updated: chrono::DateTime<chrono::Utc>,
}

/// 系统信息
#[derive(Debug, Serialize, Deserialize)]
pub struct SystemInfo {
    pub hostname: String,
    pub version: String,
    pub uptime_secs: u64,
    pub cpu_count: usize,
    pub memory_total_mb: u64,
    pub memory_used_mb: u64,
    pub load_average: Vec<f64>,
    pub disk_usage: Vec<DiskInfo>,
}

/// 磁盘信息
#[derive(Debug, Serialize, Deserialize)]
pub struct DiskInfo {
    pub name: String,
    pub total_gb: u64,
    pub used_gb: u64,
    pub available_gb: u64,
    pub usage_percent: f64,
}

/// 查询参数
#[derive(Debug, Deserialize)]
pub struct QueryParams {
    pub limit: Option<usize>,
    pub offset: Option<usize>,
    pub filter: Option<String>,
}

/// 应用状态
pub struct AppState {
    // 这里会包含对管理框架的引用
}

/// 健康检查端点
pub async fn health_check() -> Json<ApiResponse<HashMap<String, String>>> {
    let mut status = HashMap::new();
    status.insert("status".to_string(), "healthy".to_string());
    status.insert("version".to_string(), "0.1.0".to_string());
    status.insert("timestamp".to_string(), chrono::Utc::now().to_rfc3339());
    
    Json(ApiResponse::success(status))
}

/// 列出所有组件
pub async fn list_components(
    Query(params): Query<QueryParams>,
) -> Result<Json<ApiResponse<Vec<ComponentInfo>>>, StatusCode> {
    // 模拟组件数据
    let components = vec![
        ComponentInfo {
            name: "messaging".to_string(),
            version: "0.1.0".to_string(),
            status: ComponentStatus::Running,
            config: serde_json::json!({"enabled": true}),
            last_updated: chrono::Utc::now(),
        },
        ComponentInfo {
            name: "monitoring".to_string(),
            version: "0.1.0".to_string(),
            status: ComponentStatus::Running,
            config: serde_json::json!({"interval": 30}),
            last_updated: chrono::Utc::now(),
        },
    ];
    
    let filtered_components = if let Some(limit) = params.limit {
        components.into_iter().take(limit).collect()
    } else {
        components
    };
    
    Ok(Json(ApiResponse::success(filtered_components)))
}

/// 获取单个组件信息
pub async fn get_component(
    Path(name): Path<String>,
) -> Result<Json<ApiResponse<ComponentInfo>>, StatusCode> {
    // 模拟获取组件信息
    let component = ComponentInfo {
        name: name.clone(),
        version: "0.1.0".to_string(),
        status: ComponentStatus::Running,
        config: serde_json::json!({"enabled": true}),
        last_updated: chrono::Utc::now(),
    };
    
    Ok(Json(ApiResponse::success(component)))
}

/// 启动组件
pub async fn start_component(
    Path(name): Path<String>,
) -> Result<Json<ApiResponse<String>>, StatusCode> {
    tracing::info!("启动组件: {}", name);
    Ok(Json(ApiResponse::success(format!("组件 {} 启动成功", name))))
}

/// 停止组件
pub async fn stop_component(
    Path(name): Path<String>,
) -> Result<Json<ApiResponse<String>>, StatusCode> {
    tracing::info!("停止组件: {}", name);
    Ok(Json(ApiResponse::success(format!("组件 {} 停止成功", name))))
}

/// 重启组件
pub async fn restart_component(
    Path(name): Path<String>,
) -> Result<Json<ApiResponse<String>>, StatusCode> {
    tracing::info!("重启组件: {}", name);
    Ok(Json(ApiResponse::success(format!("组件 {} 重启成功", name))))
}

/// 更新组件配置
pub async fn update_component_config(
    Path(name): Path<String>,
    Json(config): Json<serde_json::Value>,
) -> Result<Json<ApiResponse<String>>, StatusCode> {
    tracing::info!("更新组件配置: {} -> {:?}", name, config);
    Ok(Json(ApiResponse::success(format!("组件 {} 配置更新成功", name))))
}

/// 获取系统信息
pub async fn system_info() -> Json<ApiResponse<SystemInfo>> {
    let sys_info = SystemInfo {
        hostname: gethostname::gethostname().to_string_lossy().to_string(),
        version: "0.1.0".to_string(),
        uptime_secs: 86400, // 模拟1天运行时间
        cpu_count: num_cpus::get(),
        memory_total_mb: 8192,
        memory_used_mb: 4096,
        load_average: vec![0.5, 0.6, 0.7],
        disk_usage: vec![
            DiskInfo {
                name: "/".to_string(),
                total_gb: 100,
                used_gb: 45,
                available_gb: 55,
                usage_percent: 45.0,
            }
        ],
    };
    
    Json(ApiResponse::success(sys_info))
}

/// 获取系统指标
pub async fn system_metrics() -> Json<ApiResponse<HashMap<String, f64>>> {
    let mut metrics = HashMap::new();
    metrics.insert("cpu_usage_percent".to_string(), 25.5);
    metrics.insert("memory_usage_percent".to_string(), 50.0);
    metrics.insert("disk_usage_percent".to_string(), 45.0);
    metrics.insert("network_in_mbps".to_string(), 10.2);
    metrics.insert("network_out_mbps".to_string(), 5.8);
    
    Json(ApiResponse::success(metrics))
}

/// 获取应用配置
pub async fn get_config() -> Json<ApiResponse<serde_json::Value>> {
    let config = serde_json::json!({
        "server": {
            "host": "0.0.0.0",
            "port": 8080
        },
        "auth": {
            "enabled": true,
            "jwt_secret": "***"
        },
        "logging": {
            "level": "info",
            "format": "json"
        }
    });
    
    Json(ApiResponse::success(config))
}

/// 更新应用配置
pub async fn update_config(
    Json(config): Json<serde_json::Value>,
) -> Result<Json<ApiResponse<String>>, StatusCode> {
    tracing::info!("更新应用配置: {:?}", config);
    Ok(Json(ApiResponse::success("配置更新成功".to_string())))
}

/// 获取日志
#[derive(Debug, Deserialize)]
pub struct LogQuery {
    pub level: Option<String>,
    pub limit: Option<usize>,
    pub since: Option<String>,
}

pub async fn get_logs(
    Query(query): Query<LogQuery>,
) -> Json<ApiResponse<Vec<serde_json::Value>>> {
    let logs = vec![
        serde_json::json!({
            "timestamp": "2024-01-20T10:30:00Z",
            "level": "INFO",
            "message": "应用启动成功",
            "component": "main"
        }),
        serde_json::json!({
            "timestamp": "2024-01-20T10:30:01Z", 
            "level": "DEBUG",
            "message": "组件初始化",
            "component": "messaging"
        }),
    ];
    
    Json(ApiResponse::success(logs))
}

/// 创建管理 API 路由
pub fn create_api_routes() -> Router {
    Router::new()
        // 健康检查
        .route("/health", get(health_check))
        
        // 组件管理
        .route("/api/v1/components", get(list_components))
        .route("/api/v1/components/:name", get(get_component))
        .route("/api/v1/components/:name/start", post(start_component))
        .route("/api/v1/components/:name/stop", post(stop_component))
        .route("/api/v1/components/:name/restart", post(restart_component))
        .route("/api/v1/components/:name/config", put(update_component_config))
        
        // 系统信息
        .route("/api/v1/system/info", get(system_info))
        .route("/api/v1/system/metrics", get(system_metrics))
        
        // 配置管理
        .route("/api/v1/config", get(get_config))
        .route("/api/v1/config", put(update_config))
        
        // 日志查询
        .route("/api/v1/logs", get(get_logs))
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum_test::TestServer;

    #[tokio::test]
    async fn test_health_check() {
        let app = create_api_routes();
        let server = TestServer::new(app).unwrap();
        
        let response = server.get("/health").await;
        response.assert_status_ok();
        
        let json: ApiResponse<HashMap<String, String>> = response.json();
        assert!(json.success);
    }

    #[tokio::test]
    async fn test_list_components() {
        let app = create_api_routes();
        let server = TestServer::new(app).unwrap();
        
        let response = server.get("/api/v1/components").await;
        response.assert_status_ok();
        
        let json: ApiResponse<Vec<ComponentInfo>> = response.json();
        assert!(json.success);
        assert!(json.data.unwrap().len() >= 2);
    }

    #[tokio::test]
    async fn test_system_info() {
        let app = create_api_routes();
        let server = TestServer::new(app).unwrap();
        
        let response = server.get("/api/v1/system/info").await;
        response.assert_status_ok();
        
        let json: ApiResponse<SystemInfo> = response.json();
        assert!(json.success);
        let info = json.data.unwrap();
        assert!(!info.hostname.is_empty());
        assert!(info.cpu_count > 0);
    }
}